package net.oschina.bilbodai.common.beanutil.property.mapping;

import com.google.common.base.Preconditions;
import net.oschina.bilbodai.common.beanutil.property.Property;

import java.util.HashMap;
import java.util.Map;

/**
 * @author daimao  Date: 2016/12/27 Time: 下午3:16
 * @version $Id$
 */
public class DefaultPropertyMapping implements PropertyMapping {

    private final Map<String, MappingProperty> keyToValueMappingMap;

    public DefaultPropertyMapping(Map<String, MappingProperty> keyToValueMappingMap) {
        Preconditions.checkNotNull(keyToValueMappingMap);
        this.keyToValueMappingMap = keyToValueMappingMap;
    }

    @Override
    public Map<String, Object> from(Object target) {
        Preconditions.checkNotNull(target);
        Map<String, Object> mappingMap = new HashMap<>(keyToValueMappingMap.size());
        for (Map.Entry<String, MappingProperty> entry : keyToValueMappingMap.entrySet()) {
            MappingProperty mappingProperty = entry.getValue();
            if (mappingProperty instanceof SimpleMappingProperty) {
                mappingMap.put(entry.getKey(), mappingProperty.getValue(target));
            } else if (mappingProperty instanceof CollectMappingProperty) {
                mappingMap.putAll(((CollectMappingProperty)mappingProperty).getValue(target));
            }
        }
        return mappingMap;
    }

}